package cn.edu.sdjzu.mocige_server.config.jwt;

import cn.edu.sdjzu.mocige_server.service.jwt.JwtService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtService jwtService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String authHeader = request.getHeader("Authorization");// 获取请求头中的Authorization字段
        if (authHeader != null && authHeader.startsWith("Bearer ")) {// 判断Authorization字段是否以"Bearer "开头
            String token = authHeader.substring(7);// 从Authorization字段中截取"Bearer "后面的部分，即令牌
            if (jwtService.validateToken(token)) {
                String username = jwtService.getUsernameFromToken(token);// 从令牌中获取用户名
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(// 创建一个UsernamePasswordAuthenticationToken对象，用于表示用户已通过身份验证
                        username, null, null);
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));// 设置认证详情
                SecurityContextHolder.getContext().setAuthentication(authentication);// 将认证信息保存到SecurityContextHolder中
            }
        }
        filterChain.doFilter(request, response);
    }
}
